package com.nguc.ngucpractice.service.impl;

import com.nguc.ngucpractice.common.entity.Result;
import com.nguc.ngucpractice.dao.RoleDao;
import com.nguc.ngucpractice.pojo.Role;
import com.nguc.ngucpractice.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;

    @Override
    public Result findAllRole() {
        Result result = new Result();
        List<Role> roles = roleDao.selectAll();
        result.setStatus("0");
        result.setData(roles);
        return result;
    }

    @Override
    public Result addRole(String roleName) {
        Result result = new Result();
        List<Role> roleList = roleDao.selectByRoleName(roleName);
        if (!CollectionUtils.isEmpty(roleList)) {
            result.setStatus("1");
            result.setData("角色名称已经存在");
            return result;
        }
        Role role = new Role();
        role.setRoleName(roleName);
        role.setCreateTime(new Date());
        int i = roleDao.insert(role);
        if (i < 0) {
            result.setStatus("1");
            result.setData("插入数据库失败");
            return result;
        }
        result.setStatus("0");
        result.setData(role);
        return result;
    }

    @Override
    public Result updateRole(Role role) {
        Result result = new Result();
        Integer count = roleDao.selCountById(role.getId());
        if (count == 0) {
            result.setStatus("1");
            result.setData("没有这个角色，请刷新重试");
            return result;
        }
        int i = roleDao.updateByPrimaryKey(role);
        if (i < 0) {
            result.setStatus("1");
            result.setData("更新失败");
            return result;
        }
        result.setStatus("0");
        result.setData(role);
        return result;
    }

}
